<template>
  <div class="header">
    <el-input
      :autosize="{ minRows: 8, maxRows: 4 }"
      type="textarea"
      v-model="text"
      placeholder="请输入需要转化为语音的文本"
    ></el-input>
    <el-button @click="playVoice">点击播放</el-button>
    <el-button @click="handleStop">结束播放</el-button>
  </div>
</template>

<script setup>
import { reactive, toRefs } from "vue";
const synth = window.speechSynthesis;
const msg = new SpeechSynthesisUtterance();
const data = reactive({
  text: "",
});

const { text } = toRefs(data);

const playVoice = () => {
  handleSpeak(data.text); // 传入需要播放的文字
  ElMessage({
    showClose: true,
    message: "开始播放",
    type: "success",
  });
};

// 语音播报的函数
const handleSpeak = (text) => {
  msg.text = text; // 文字内容
  msg.lang = "zh-CN"; // 使用的语言:中文
  msg.volume = 1; // 声音音量：1
  msg.rate = 1; // 语速：1
  msg.pitch = 1; // 音高：1
  synth.speak(msg); // 播放
};

// 语音停止
const handleStop = (e) => {
  msg.text = e;
  msg.lang = "zh-CN";
  synth.cancel(msg);
  ElMessage({
    showClose: true,
    message: "播放结束",
    type: "error",
  });
};


</script>

<style lang="less" scoped>
.header {
  .el-button {
    margin-top: 8px;
  }
}
</style>
